<template>
    <div class="ad-list">
        <Form :model="formItem" ref="formItem" :inline="true" action="javascript:void(0)">
            <FormItem>
                <Input v-model="formItem.key" placeholder="输入关键词查找"></Input>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="renderTable()">查找</Button>
            </FormItem>
        </Form>
        <div class="action-btn">
            <Button size="small" @click="removeMultiple()" style="margin-right: 8px" type="error">批量删除</Button>
            <Button size="small" @click="showModal()" type="success">添加广告</Button>
        </div>
        <Table border ref="adList" :columns="tableColumn" :data="dataList" :loading="dataLoading" @on-selection-change="changeData($event)">
            <template #title="{ row }">
                <div class="clearfix" style="padding:10px;">
                    <img :src="row.thumb" width="120" alt="" class="f-l" style="padding:10px;background:#eee;margin-right:10px;">
                    <a :href="row.url" target="_blank" style="font-size:16px;line-height:2;display:block;">[{{ row.ad_pos.name }}] - {{ row.title }}</a>
                    <p>{{ row.starttime }} - {{ row.endtime }}</p>
                </div>
            </template>
            <template #sort="{row}">
                <InputNumber v-model="row.sort" size="small" :min="0" @on-change="sortDetail(row.id,$event)" />
            </template>
            <template #status="{ row }">
                <Tag color="green" v-if="row.status">正常</Tag>
                <Tag color="volcano" v-if="row.status == false">关闭</Tag>
            </template>
            <template #action="{ row, index }">
                <Button type="info" size="small" style="margin-right: 5px;float:left" @click="showEdit(row.id)">编辑</Button>
                <Button type="error" size="small" @click="removeDetail(index,row.id)">删除</Button>
            </template>
        </Table>
        <!-- 分页 -->
        <div class="table-page">
            <Page size="small" ref="listPage" :total="pages.total" :model-value="pages.current" :page-size="pages.size" show-elevator show-total @on-change="changePage"></Page>
        </div>
        <!-- 需要全屏时添加这句 :mask="false" class-name="idw100" -->
        <Drawer :closable="false" :mask-closable="false" :scrollable="true" title="详情" width="640" v-model="showModalStatus">
            <Spin size="large" fix v-if="loading"></Spin>
            <Form :model="detailInfo" ref="adValidate" label-position="right" :label-width="80" :rules="adValidate" action="javascript:void(0)">
                <FormItem label="广告位" prop="pos_id">
                    <Select v-model="detailInfo.pos_id" :style="{'width':'240px'}">
                        <Option v-for="item in adposList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="名称" prop="title">
                    <Input v-model="detailInfo.title" placeholder="输入名称"></Input>
                </FormItem>
                <FormItem label="上传图片">
                    <upload-thumb v-model="detailInfo.thumb" ref="uploadthumb" :defaultList="thumbList"></upload-thumb>
                </FormItem>
                <FormItem label="URL" prop="url">
                    <Input v-model="detailInfo.url" placeholder="输入链接地址"></Input>
                </FormItem>
                <FormItem label="开始时间">
                    <DatePicker :model-value="startAt" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="开始时间" style="width: 200px" @on-change="startCharge($event)"></DatePicker>
                </FormItem>
                <FormItem label="结束时间">
                    <DatePicker :model-value="endAt" format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="结束时间" style="width: 200px" @on-change="endCharge($event)"></DatePicker>
                </FormItem>
                <FormItem label="状态">
                    <i-switch :true-value="1" :false-value="0" v-model="detailInfo.status">
                        <template #open>正常</template>
                        <template #close>禁用</template>
                    </i-switch>
                </FormItem>
                <FormItem label="排序">
                    <InputNumber :max="9999" :min="0" v-model="detailInfo.sort"></InputNumber>
                </FormItem>
                <FormItem>
                    <Button style="margin-right: 8px" @click="showModalStatus = false">取消</Button>
                    <Button type="primary" @click="handleSubmit('adValidate')">提交</Button>
                </FormItem>
            </Form>
        </Drawer>
    </div>
    </template>
    
    <script>
    import UploadThumb from '../.././components/thumb'
    export default {
        name: 'Ad',
        data() {
            return {
                detail_id:0,
                loading: false,
                dataLoading: true,
                formItem: {
                    'key': ''
                },
                pages: {
                    current: 1,
                    total: 0,
                    size: 10
                },
                tableColumn: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center',
                    },
                    {
                        title: 'Id',
                        key: 'id',
                        width: 60,
                    },
                    {
                        title: '名称',
                        minWidth: 300,
                        slot: 'title',
                    },
                    {
                        title: '排序',
                        width: 100,
                        slot: 'sort',
                    },
                    {
                        title: '状态',
                        slot: 'status',
                        width: 90
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 130
                    }
                ],
                dataList: [],
                detailInfo: {
                    pos_id: 0,
                    title: '',
                    thumb: null,
                    url: '',
                    starttime: '',
                    endtime: '',
                    sort: 0,
                    status: 1
                },
                startAt:'',
                endAt:'',
                showModalStatus: false,
                adValidate: {
                    pos_id: [
                        { required: true, type: 'integer', message: '广告位必须填写', trigger: 'change' }
                    ],
                    title: [
                        { required: true, message: '链接名称必须填写', trigger: 'blur' }
                    ],
                    url: [
                        { required: true, message: '链接 URL 必须填写', trigger: 'blur' }
                    ]
                },
                adposList:[],
                thumbList:[],
                selectData:[],
            }
        },
        created() {
            // 取数据
            this.getTableList();
            this.$api.adpos.list({page:1,size:100000}).then(res => {
                this.adposList = res.result.list;
            });
        },
        // 组件
        components: {
            UploadThumb
        },
        methods: {
            startCharge(e){
                this.startAt = e;
                this.detailInfo.starttime = e;
            },
            endCharge(e){
                this.endAt = e;
                this.detailInfo.endtime = e;
            },
            changePage() {
                this.pages.current = this.$refs['listPage'].currentPage;
                this.getTableList();
            },
            changeData(index) {
                this.selectData = index
            },
            getTableList() {
                var params = this.formItem;
                params.size = this.pages.size;
                params.page = this.pages.current;
                this.dataLoading = true;
                this.$api.ad.list(params).then(res => {
                    this.dataList = res.result.list;
                    this.pages.total = res.result.count
                }).finally(e=>{
                    this.dataLoading = false;
                });
            },
            renderTable() {
                this.pages.currentPage = 1;
                this.getTableList();
            },
            showModal() {
                this.showModalStatus = !this.showModalStatus;
                this.detailInfo = {
                    pos_id: 0,
                    title: '',
                    thumb: null,
                    url: '',
                    starttime: '',
                    endtime: '',
                    sort: 0,
                    status: 1
                };
                this.startAt = '';
                this.endAt = '';
                this.detail_id = 0;
                this.thumbList = [];
            },
            handleSubmit(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        this.loading = true;
                        // 图片
                        if (this.$refs['uploadthumb'].uploadList.length) {
                            this.detailInfo.thumb = this.$refs['uploadthumb'].uploadList[0].url;
                        }else{
                            this.loading = false;
                            this.$Message.error('请上传图片');
                            return;
                        }
                        if (this.detail_id == 0) {
                            this.$api.ad.create(this.detailInfo).then(res => {
                                this.getTableList();
                                this.showModalStatus = !this.showModalStatus;
                            }).finally(res => {
                                this.loading = false;
                            });
                        }else{
                            this.detailInfo.detail_id = this.detail_id;
                            this.$api.ad.update(this.detailInfo).then(res => {
                                this.getTableList();
                                this.showModalStatus = !this.showModalStatus;
                            }).finally(res => {
                                this.loading = false;
                            });
                        }
                    } else {
                        this.$Message.error('请检查输入的信息是否正确');
                        this.loading = false
                    }
                })
            },
            showEdit(id){
                this.detail_id = id;
                this.loading = true;
                this.$api.ad.detail({detail_id:id}).then(res => {
                    if (res.code == 200) {
                        this.showModalStatus = !this.showModalStatus;
                        this.detailInfo = res.result
                        this.startAt = this.detailInfo.starttime;
                        this.endAt = this.detailInfo.endtime;
                        this.loading = false;
                        this.thumbList = [];
                        if (res.result.thumb != '' && res.result.thumb != null) {
                            this.thumbList = [{ 'name': '图片文件', 'url': res.result.thumb, 'status': 'finished' }];
                        }
                    }
                })
            },
            removeDetail(index, id) {
                this.$Modal.confirm({
                    title: '警告',
                    content: '<p>此操作不可恢复，三思而后行</p>',
                    onOk: () => {
                        this.$api.ad.remove({ detail_id: [id] }).then(res => {
                            this.dataList.splice(index, 1);
                        });
                    }
                });
            },
            sortDetail (id,value) {
                this.$api.ad.sort({ detail_id: id,sort:value }).then(res => {});
            },
            removeMultiple() {
                this.$Modal.confirm({
                    title: '警告',
                    content: '<p>此操作不可恢复，三思而后行</p>',
                    onOk: () => {
                        var ids = [];
                        this.selectData.forEach((item, index) => {
                            ids.push(item.id);
                        })
                        this.$api.ad.remove({ detail_id: ids }).then(res => {
                            this.getTableList();
                        });
                    }
                });
            },
        }
    }
    </script>
    